﻿using System;
using System.Collections.Generic;
using System.Text;

namespace HGZP.DAL
{
  public  class InsertWhereCondition
    {
        static public string WhereCondition(string sOldSqlString, string sWhere)
        {
            sOldSqlString = sOldSqlString.ToLower();
            if (sWhere == "All") { return sOldSqlString; } //全部 则返回原字符串
            if (sWhere.Trim() != string.Empty)
            {
                int iWherePosition = sOldSqlString.IndexOf("where");
                int iorderPosition = sOldSqlString.IndexOf("order by");
                int iFrom = sOldSqlString.IndexOf("from");
                int igroup = sOldSqlString.IndexOf("group by");
                if (iWherePosition >= 0)
                {
                    sOldSqlString = sOldSqlString.Insert(iWherePosition + 6, sWhere);
                }
                else
                {
                    if (igroup >= 0)
                    {
                        sOldSqlString = sOldSqlString.Insert(igroup - 1, " where " + sWhere.Substring(0, sWhere.Length - 4));
                    }
                    else
                    {
                        if (iorderPosition >= 0 && iorderPosition > iFrom)
                        {
                            sOldSqlString = sOldSqlString.Insert(iorderPosition - 1, " where " + sWhere.Substring(0, sWhere.Length - 4));
                        }
                        else
                        {
                            sOldSqlString += " where " + sWhere.Substring(0, sWhere.Length - 4);
                        }
                    }
                }
            }
            return sOldSqlString;
        }
    }
}
